import { LockOutlined, UserOutlined, } from '@ant-design/icons';
import { Alert, message, } from 'antd';
import React, { useState } from 'react';
import { ProFormText, LoginForm } from '@ant-design/pro-form';
import { useIntl, history, FormattedMessage, SelectLang,useModel} from 'umi';
import { login } from '@/services/ant-design-pro/api';
import { useLocalStorageState } from 'ahooks'

import styles from './index.less';


const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type,] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
const fetchUserInfo = async () => {
  const userInfo = await initialState?.fetchUserInfo?.();      
  if (userInfo) {
    await setInitialState((s:any) => ({
      ...s,
      currentUser: userInfo,
    }));
  }
};
  // 本地数据
  const [, setLocal] = useLocalStorageState('userinfo');
  const intl = useIntl();
  const { status, type: loginType } = userLoginState;
  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录接口
      const msg = await login({ ...values });
     
      if ((msg as any).statusCode === 200) {
        //  跳转列表
        message.success('登录成功');
        setLocal((msg as any).data);
        localStorage.setItem('token',(msg as any).data.token);
        await fetchUserInfo();
        history.push('/home');
        
      }
      // 如果失败去设置用户错误信息
      setUserLoginState(msg);
    } catch (error) {
      message.error('登录失败');
    }
  };


  return (
    <div className={styles.container}>
      <div className={styles.lang} data-lang>
        {SelectLang && <SelectLang />}
      </div>
      <div className={styles.content}>
        <div className={styles.backImg}>
         <img src='https://lijiaju-none.oss-cn-beijing.aliyuncs.com/back.jpg' alt="" />
        </div>
        <div className={styles.loginbox}>
          <LoginForm
            subTitle="系统登录"
            initialValues={{
              autoLogin: true,
            }}
            onFinish={async (values) => {
              await handleSubmit(values as API.LoginParams);
            }}
          >
            {/* 登录失败 */}
            {status === 'error' && loginType === 'account' && (
              <LoginMessage
                content={intl.formatMessage({
                  id: 'pages.login.accountLogin.errorMessage',
                  defaultMessage: '账户或密码错误(admin/ant.design)',
                })}
              />
            )}
            {/* 登录区域 */}
            {type === 'account' && (
              <>
                <ProFormText
                  name="name"
                  fieldProps={{
                    size: 'large',
                    prefix: <UserOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={intl.formatMessage({
                    id: 'pages.login.username.placeholder',
                    defaultMessage: '用户名: admin',
                  })}
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.username.required"
                          defaultMessage="请输入用户名!"
                        />
                      ),
                    },
                  ]}
                />
                <ProFormText.Password
                  name="password"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={intl.formatMessage({
                    id: 'pages.login.password.placeholder',
                    defaultMessage: '密码: ant.design',
                  })}
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.password.required"
                          defaultMessage="请输入密码！"
                        />
                      ),
                    },
                  ]}
                />
              </>
            )}
            <div
              style={{
                marginBottom: 24,
              }}
            >
            </div>
            <span onClick={()=>{
              history.push('/user/register')
            }} style={{display:'inline-block',marginBottom:'20px'}}>Or、去注册</span>
          </LoginForm>
        </div>

      </div>
    </div>
  );
};

export default Login;
